﻿using System.Collections;

/// <summary>
/// 结算
/// </summary>
public class Game_SettState : GameState
{
	static Game_SettState _inst;

	public static Game_SettState inst {
		get {
			if (_inst == null) {
				_inst = new Game_SettState ();
			}
			return _inst;
		}
	}

	public override void Enter ()
	{
		base.Enter ();

		DebugInfo.Log ("Enter Game_RoundSettState");

		if (!GameDataKernel.inst.roundSett.isFinal) {
			UIGameRoundSett.Popup ();
		} else {
			UIGameTotalSett.Popup ();
		}
	}

	public override void Leave ()
	{
		DebugInfo.Log ("Leave Game_RoundSettState");

		base.Leave ();
	}

	public override bool HandleMessage (BaseProceduar.Message message)
	{
		switch (message.msgId) {
		case Commands.CMD_MOD_MSG:
			switch (message.iParam) {
			case GameCommands.CMD_PREPARE_GAME:
				if (!GameDataKernel.inst.mainPlayer.master) {
					// 发送就绪
					Hashtable reqArgs = new Hashtable ();
					reqArgs ["roomId"] = GameDataKernel.inst.roomId;
					reqArgs ["uid"] = DataKernel.inst.userInfo.uid;

					UIRootController.inst.ShowMask (true);
					NetIOController.inst.SendMessage (
						new IOMessage (IOCmds.CMSG_PLAYER_CONTINUE, 
							IOStates.STATE_OK, new HashtableEx (reqArgs)));
				}

				GameDataKernel.inst.ResetForContinue ();
				GameProcedure.inst.SwitchState (Game_WaitingState.inst);

				// 恢复消息执行
				GameController.inst.proceduar.paused = false;
				return true;

			case GameCommands.CMD_EXIT_GAME:
				// 恢复消息执行
				GameController.inst.proceduar.paused = false;
				return true;
			}
			break;
		}

		return base.HandleMessage (message);
	}

	public override bool ProcessPacket (IOMessage message)
	{
		switch (message.code) {
		case IOCmds.SMSG_SET_ROOM_FINISHED:
			UIRootController.inst.ShowMask (true);
			NetIOController.inst.isGame = false;
			NetIOController.inst.ConnectToNewURL (Constants.LOGIN_URL);
			return true;
		case IOCmds.WS_CONN_OPEN:
			// 与服务器的连接打开
			UIRootController.inst.ShowMask (false);
			if (!NetIOController.inst.isGame) {
				if (_reconnecting) {
					UIGameReconnectWindow.CloseWindow ();
					GameController.inst.SwitchTo (GameProcedure.inst);
				} else {
					UIGameTotalSett.CloseWindow ();
					GameController.inst.SwitchTo (HomeProcedure.inst);
				}
			}
			return true;
		case IOCmds.WS_CONN_CLOSED:
			if (_reconnecting) {
				NetIOController.inst.Connect (null);
			} else {
				if (!NetIOController.inst.isGame) {
					// 正在重新连接到中央服务器
					UIRootController.inst.ShowMask (true);
					NetIOController.inst.Connect (null);
				} else {
					UIGameTotalSett.CloseWindow ();

					// 游戏服务器掉线，重新连接
					UIGameReconnectWindow.Popup ();
				}
			}
			return true;
		}
		return base.ProcessPacket (message);
	}
}
